package com.zhongyewx.teachercert.framework.okhttp;


import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.zhongyewx.teachercert.BuildConfig;
import com.zhongyewx.teachercert.api.ZYConstants;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retofit网络请求
 * Created by HXL on 2017/3/20.
 **/
public class ZYRetrofitUtils {
    private Retrofit mInvoiceRetrofit;
    private Retrofit mRetrofit;
    private static ZYRetrofitUtils mZyRetrofitUtils;
    private static final int READ_TIMEOUT = 30;//读取超时时间,单位  秒
    private static final int CONN_TIMEOUT = 30;//连接超时时间,单位  秒

    public static Retrofit newInstence() {
        if (mZyRetrofitUtils == null) {
            synchronized (ZYRetrofitUtils.class) {
                if (mZyRetrofitUtils == null) {
                    mZyRetrofitUtils = new ZYRetrofitUtils();
                }
            }
        }
        return mZyRetrofitUtils.newInstences();
    }

    public static Retrofit newInvoiceInstence() {
        if (mZyRetrofitUtils == null) {
            synchronized (ZYRetrofitUtils.class) {
                if (mZyRetrofitUtils == null) {
                    mZyRetrofitUtils = new ZYRetrofitUtils();
                }
            }
        }
        return mZyRetrofitUtils.newInvoiceInstences();
    }

    private Retrofit newInstences() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                if (message.startsWith("{") || message.startsWith("<--")) {
                    Log.i("HXLLog", "retrofitBack = " + message);
                }
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = null;
        if(BuildConfig.IS_OFFICIAL_SITE){//正式站
            client = new OkHttpClient
                    .Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.MINUTES)
                    .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                    .build();//初始化一个client,不然retrofit会自己默认  添加一个
        } else {
            client = new OkHttpClient
                    .Builder()
                    .addInterceptor(loggingInterceptor)
                    .readTimeout(READ_TIMEOUT, TimeUnit.MINUTES)
                    .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                    .build();//初始化一个client,不然retrofit会自己默认  添加一个
        }

        if (mRetrofit == null) {
            Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
            //到这一步创建完成
            mRetrofit = new Retrofit.Builder()
                    .client(client)//添加一个client,不然retrofit会自己默认添加一个
                    .baseUrl(ZYConstants.API_URL)
                    .addConverterFactory(new NullOnEmptyConverterFactory())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;
    }


    private ZYRetrofitUtils() {

    }

    private Retrofit newInvoiceInstences() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                if (message.startsWith("{") || message.startsWith("<--")) {
                    Log.i("HXLLog", "retrofitBack = " + message);
                }
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = null;
        if(BuildConfig.IS_OFFICIAL_SITE){//正式站
            client = new OkHttpClient
                    .Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.MINUTES)
                    .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                    .build();//初始化一个client,不然retrofit会自己默认  添加一个
        } else {
            client = new OkHttpClient
                    .Builder()
                    .addInterceptor(loggingInterceptor)
                    .readTimeout(READ_TIMEOUT, TimeUnit.MINUTES)
                    .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                    .build();//初始化一个client,不然retrofit会自己默认  添加一个
        }

        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();

        if (mRetrofit == null) {
            mInvoiceRetrofit = new Retrofit.Builder()
                    .client(client)//添加一个client,不然retrofit会自己默认添加一个
                    .baseUrl("https://nnfp.jss.com.cn/shop/buyer/allow/")// 测试域名 https://nnfpdev.jss.com.cn/shop/buyer/allow/  正式：https://nnfp.jss.com.cn/shop/buyer/allow/
                    .addConverterFactory(new NullOnEmptyConverterFactory())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return mInvoiceRetrofit;
    }


    private static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            Class<T> rawType = (Class<T>) type.getRawType();
            if (rawType != String.class) {
                return null;
            }
            return (TypeAdapter<T>) new StringNullAdapter();
        }
    }

    private static class StringNullAdapter extends TypeAdapter<String> {
        @Override
        public String read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return "";
            }
            if (reader.peek() == JsonToken.BEGIN_OBJECT) {
                reader.endObject();
                return null;
            }
            return reader.nextString();
        }

        @Override
        public void write(JsonWriter writer, String value) throws IOException {
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }
    }
}
